<?php

namespace App\Http\Controllers;

use App\SunPicture;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class SunPictureController extends Controller
{
    public function index()
    {
        $sunPicture = SunPicture::latest('created_at')->Paginate(8);
        return view('SunPicture.sunpicture',compact('sunPicture'));
    }

    public function destroy($id)
    {
        $sunPicture = SunPicture::find($id);
        $avatar = $sunPicture->posts_pic;
        if ($avatar != 'default.jpg') {
            Storage::disk('uploads')->exists($avatar);
            Storage::disk('uploads')->delete($avatar);
        }
        $sunPicture->delete();

        session()->flash('success', '删除成功');
        return redirect()->route('sunPicture.index');
    }

    public function edit($id)
    {
        $sunPicture = SunPicture::findOrFail($id);
        return view('SunPicture.sunpictureEdit',compact('sunPicture'));
    }

    public function update(Request $request, $id)
    {
        $sunPicture = SunPicture::findOrFail($id);

        if ($request->file('posts_pic'))
        {
            $avatar = $sunPicture->posts_pic;
            if ($avatar != 'default.jpg') {
                Storage::disk('uploads')->exists($avatar);
                Storage::disk('uploads')->delete($avatar);
            }
            $this->uploadAvatar($request);
            $sunPicture->posts_pic = $request->get('id')
                . '.' . $request->file('posts_pic')
                    ->getClientOriginalExtension();
            $sunPicture->save();
        }

        $sunPicture->update([
            'posts_content' => $request->get('posts_content'),
            'comments_count' => $request->get('comments_count'),
        ]);
        $sunPicture->save();

        session()->flash('success', '更新成功');
        return redirect()->route('sunPicture.index');
    }

    public function uploadAvatar(Request $request)
    {
        if ($request->isMethod('post') OR $request->isMethod('patch')) {

            $avatar = $request->file('posts_pic');

            if ($avatar->isValid()) {

                $realPath = $avatar->getRealPath();
                $ext = $avatar->getClientOriginalExtension();
                $masterName = $request->get('id');
                $fileName = $request->get('id'). '.' .$ext;
//              Storage::disk('uploads')->put($fileName, file_get_contents($realPath));
                //clip avatar
                Image::make($avatar)->fit(300, 300)->save(public_path('/uploads/avatars/') . $fileName);

            }
        }
    }

}
